package com.crrcdt.chatroom.controller;

import com.crrcdt.chatroom.entity.User;
import com.crrcdt.chatroom.service.UserService;
import com.crrcdt.chatroom.service.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lj on 2020/9/25.
 * @version 1.0
 */
@Controller
public class LoginController {
    @Autowired
    UserService userService;
    @RequestMapping({"/","/login","/toLogin"})
    public String toLogin(){
        return "login";
    }
    @RequestMapping("/chatroom")
    public String toChatroom(){
        return "chatroom";
    }

    @RequestMapping(value="/currentuser",method = RequestMethod.GET)
    @ResponseBody
    public User currentuser(HttpSession httpSession){
        final User currentUser = (User)httpSession.getAttribute("loginUser");
        return currentUser;
    }

    /**
     * 获取当前在线人数
     * @param currentuser
     * @return
     */
    @RequestMapping("/onlineusers")
    @ResponseBody
    public Set<String> onlineusers(@RequestParam("currentuser") String currentuser) {
        ConcurrentHashMap<String, Session> map = WebSocketServer.getSessionPools();
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        Set<String> nameset = new HashSet<String>();
        while (it.hasNext()) {
            String entry = it.next();
            if (!entry.equals(currentuser)){
                nameset.add(entry);
            }

        }
        return nameset;
    }

}
